/*  CoolJSLib JavaScript - Windows, version 0.6
 *  (c) 2010-2012 Andrei Pop, andreipop2005@gmail.com
 *  
 *  Requires: prototype.js 1.7
 *
 *  CoolJSLib is freely distributable under the terms of an MIT-style license.
 *
 *--------------------------------------------------------------------------*/

var Windows = {

    zIndex: 9000,   		// start z-index
    opacity: 0.7,   		// opacity of transparent background
	readyToCenter: false,	// used for facebook centering


    /**
     * Opens a new window
     *
     * @param windowId   
     *    mandatory, represents id of div to show
     * @param modal      
     *    optional (default true), if black layer is displayed with 0 opacity
     * @param background      
     *    optional (default true), if black layer is displayed or not (requires [modal] property also)
     * @param center          
     *    optional (default true), center on show
     * @param keepcenter      
     *    optional (default true), recenter on scroll or on resize (requires [center] property also)
     * @param allowout        
     *    optional (default true), if window can have negative coordinates
     * @param timeout         
     *    optional (default 0), autoclose in x miliseconds, 0 for disable
     * @param oncloseevt         
     *    optional (default false), procedure to call when user closes the window
     * @param centerfct
     *    optional (default false), procedure to call for centering window, overides default
     *
     * @return Object
     *   window properties. Contains original parameters plus:
     *     - windowZ, z-index of window
     *     - divZ (optional), z-index of black div
     *     - divId (optional), id of black div
    */
    OpenWindow: function(prop)
    {
        if (prop.windowId   == undefined) throw '[windowId] is required in OpenWindow';
        
        if (prop.modal      == undefined) prop.modal=true;
        if (!prop.modal) prop.background=false;
        
        if (prop.background == undefined) prop.background=true;
        if (prop.background) prop.modal=true;
        
        if (prop.center     == undefined) prop.center=true;
        if (!prop.center) prop.keepcenter=false;
        
        if (prop.keepcenter == undefined) prop.keepcenter=true;
        if (prop.keepcenter) prop.center=true;
        
        if (prop.timeout    == undefined) prop.timeout=0;
        if (prop.timeout < 0) throw '[timeout] cannot be negative in OpenWindow';
        
        if (prop.allowout   == undefined) prop.allowout=true;
        if (prop.oncloseevt == undefined) prop.oncloseevt=false;
        if (prop.centerfct  == undefined) prop.centerfct=false;
        
        if ($(prop.windowId) && $(prop.windowId).style.display == 'block') return; // exit if window is already opened
        
        if (this.objects == undefined) this.objects = new Array();
        
        var nume = prop.windowId + '_black';
        
        if (prop.modal)
        {
            if (prop.background)
                this.NewLayer(nume);
            else
            {
                var bkp = this.opacity;
                this.opacity = 0;
                this.NewLayer(nume);
                this.opacity = bkp;
            }
        }
        else
        {
            this.objects[nume] = Array();
            this.objects[nume]['divZ']    = this.zIndex;
            this.objects[nume]['windowZ'] = this.zIndex + 1;
            this.zIndex++;
        }
        
        this.objects[nume]['windowId']   = prop.windowId;
        this.objects[nume]['modal']      = prop.modal;
        this.objects[nume]['background'] = prop.background;
        this.objects[nume]['center']     = prop.center;
        this.objects[nume]['keepcenter'] = prop.keepcenter;
        this.objects[nume]['timeout']    = prop.timeout;
        this.objects[nume]['timeoutId']  = null;
        this.objects[nume]['allowout']   = prop.allowout;
        this.objects[nume]['oncloseevt'] = prop.oncloseevt;
        this.objects[nume]['centerfct']  = prop.centerfct;
        
        $(prop.windowId).setStyle({ zIndex: this.objects[nume]['windowZ'] });
        this.zIndex++;
        
        if (prop.center) this.CenterWindow(nume);
        $(prop.windowId).setStyle({
            position: 'absolute',
            display: 'block'
        }); 
        
        if (prop.timeout > 0)
            this.objects[nume]['timeoutId'] = setTimeout("Windows.CloseWindow('"+prop.windowId+"')", prop.timeout);
            
        return this.objects[nume];
    },
    
	OpenDummyWindow: function(prop)
	{
        if (prop.windowId   == undefined) throw '[windowId] is required in OpenDummyWindow';
		
		if (!$(prop.windowId))
		{
			$(document.body).insert({top: '<div id="' + prop.windowId + '"></div>'});
		}
		this.OpenWindow(prop);
	},
	
    NewLayer: function(nume)
    {
        var newName = 'blacklayer' + this.zIndex;
        
        if (this.objects == undefined) this.objects = new Array();
        
        $(document.body).insert({top: '<div id="' + newName + '"></div>'});
        $(newName).setStyle({
            position: 'absolute',
            background: 'none repeat scroll 0 0 #000000',
            left: '0px',
            top: '0px',
            width: '100%',
            height: '100%',
            display: 'none',
            opacity: this.opacity,
			filter: 'alpha(opacity='+(this.opacity*100)+')',
            zIndex: this.zIndex,
            display: 'block'
        }); 
        
    	var PageSize 			 = this.GetPageSize();
    	$(newName).style.width 	 = PageSize[0] + 'px';
    	$(newName).style.height  = PageSize[1] + 'px';
    	$(newName).style.display = 'block';
        
        this.objects[nume] = Array();
        this.objects[nume]['divId']   = newName;
        this.objects[nume]['divZ']    = this.zIndex;
        this.objects[nume]['windowZ'] = this.zIndex + 1;
        
        this.zIndex++;
        
        return this.objects[nume];
    },
    
    CloseLayer: function(nume)
    {
    	$(this.objects[nume]['divId']).style.display 	= 'none';
        $(this.objects[nume]['divId']).remove();
        
        this.objects[nume] = false;
    },
    
    ResizeLayers: function()
    {
        var PageSize = this.GetPageSize();
        
        for (var key in this.objects)
        {
            if ($(this.objects[key]['divId']))
            {
            	$(this.objects[key]['divId']).style.width 	= PageSize[0] + 'px';
            	$(this.objects[key]['divId']).style.height  = PageSize[1] + 'px';
            }
        }
    },
    
    CloseWindow: function(windowId)
    {
		if (!$(windowId)) return;
		
        $(windowId).style.display = 'none';
        var nume = windowId + '_black';
        
		if (typeof this.objects == 'undefined' || typeof this.objects[nume] == 'undefined') return;

        if (this.objects[nume]['timeoutId'] != null)
        {
            clearInterval(this.objects[nume]['timeoutId']);
            this.objects[nume]['timeoutId'] = null;
        }

		var f = false;
		if (this.objects[nume]['oncloseevt']) 
		{
			f = this.objects[nume]['oncloseevt'];
			var p = this.objects[nume];
		}
		
        if (this.objects[nume]['modal'])
            this.CloseLayer(nume);
			
		if (f) f(p);
    },
    
    CenterWindow: function(nume)
    {
        if ($(this.objects[nume]['windowId']))
        {
            var BoxId            = this.objects[nume]['windowId'];
			if (!this.objects[nume]['centerfct'])
			{
				var BoxDimension 	 = this.GetBoxDimensions(BoxId);
				var PageDimensions   = this.GetPageDimensions();
				var PageScroll       = this.GetPageScroll();

				var PositionLeft = ((PageDimensions.width  - BoxDimension.width)  / 2).round() + PageScroll.x;
				var PositionTop  = ((PageDimensions.height - BoxDimension.height) / 2).round() + PageScroll.y;

				if (!this.objects[nume]['allowout'])
				{
					if (PositionLeft < 0) PositionLeft = 0;
					if (PositionTop < 0)  PositionTop  = 0;
				}

				try {
					$(BoxId).style.left = PositionLeft + 'px';
					$(BoxId).style.top  = PositionTop  + 'px';
				} catch (e) {}
				
				this.ResizeLayers();
			}
			else
			{
				var f = this.objects[nume]['centerfct'];
				f(BoxId);
			}
        }
    },
    
    CenterWindowById: function(BoxId)
    {
        for (var key in this.objects)
        {
            if ($(this.objects[key]['windowId']) && this.objects[key]['windowId'] == BoxId)
            {
				this.CenterWindow(key);
            }
        }
    },
    
	FBCenterWindow: function(divName)
	{
		if (this.readyToCenter)
		{
			FB.Canvas.getPageInfo(
				function(info) {
					if ($(divName))
					{
						var _top = (info.scrollTop+info.clientHeight/2-$(divName).getHeight()/2 - 30);
						if (_top < 0) _top = 0;
						
						$(divName).style.top = _top + 'px';
						$(divName).style.left = ((760 - $(divName).getWidth())/2) + 'px';
					}
				}
			);
		}
		else
		{
			setTimeout("Windows.FBCenterWindow('"+divName+"');", 1000);
		}
	},

    RecenterWindows: function()
    {
        for (var key in this.objects)
        {
            if ($(this.objects[key]['windowId']))
            {
                if (this.objects[key]['center'] && this.objects[key]['keepcenter'])
                    this.CenterWindow(key);
            }
        }
    },
    
    GetPageDimensions: function()
    {
        var WindowWidth;
        var WindowHeight;
        
    	if (self.innerHeight) 
    	{	// all except Explorer
    		if (document.documentElement.clientWidth)
            {
    			WindowWidth = document.documentElement.clientWidth; 
    		} 
            else
            {
    			WindowWidth  = self.innerWidth;
    		}
    		WindowHeight = self.innerHeight;
    	} 
        else if (document.documentElement && document.documentElement.clientHeight) 
        {   // Explorer 6 Strict Mode
    		WindowWidth  = document.documentElement.clientWidth;
    		WindowHeight = document.documentElement.clientHeight;
    	}
        else if (document.body) 
        {   // other Explorers
    		WindowWidth  = document.body.clientWidth;
    		WindowHeight = document.body.clientHeight;
    	}
        
        return {width: WindowWidth, height: WindowHeight};
    },
    
    GetBoxDimensions: function(BoxId)
    {
		//var layout = new Element.Layout(BoxId);
		//return {width: layout.get('width'), height: layout.get('height')};
		
        var BoxDimension 	 = $(BoxId).getDimensions();
        
        var BoxWidth 		 = BoxDimension.width;
        var BoxHeight 		 = BoxDimension.height;
        
        if (BoxWidth == 0)
        {
        	BoxWidth = $(BoxId).style.width;
        	BoxWidth = parseInt(BoxWidth.replace('px', ''));
        }
        if (BoxHeight == 0)
        {
        	BoxHeight = $(BoxId).style.height;
        	BoxHeight = parseInt(BoxHeight.replace('px', ''));
        }
        
        return {width: BoxWidth, height: BoxHeight};
    },
    
    GetPageScroll: function()
    {
        var WindowScroll = document.viewport.getScrollOffsets();
        var xScroll, yScroll;
        
    	if (window.innerHeight && window.scrollMaxY) 
    	{	
    		xScroll = window.innerWidth  + window.scrollMaxX;
    		yScroll = window.innerHeight + window.scrollMaxY;
    	} 
    	else if (document.body.scrollHeight > document.body.offsetHeight)
    	{ // all but Explorer Mac
    		xScroll = document.body.scrollWidth;
    		yScroll = document.body.scrollHeight;
    	} 
    	else 
    	{ // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
    		xScroll = document.body.offsetWidth;
    		yScroll = document.body.offsetHeight;
    	}
        
        return {x: WindowScroll[0], y: WindowScroll[1], maxX: 0, maxY: 0};
    },
    
    GetPageSize: function() // use doctype html/xhtml Transitional
    {
    	/*
		var layout = new Element.Layout(document.body);
		return [layout.get('width'), layout.get('height')];
		*/
		
        var xScroll, yScroll;
		
    	if (window.innerHeight && window.scrollMaxY) 
    	{	
    		xScroll = window.innerWidth + window.scrollMaxX;
    		yScroll = window.innerHeight + window.scrollMaxY;
    	} 
    	else if (document.body.scrollHeight > document.body.offsetHeight)
    	{ // all but Explorer Mac
    		xScroll = document.body.scrollWidth;
    		yScroll = document.body.scrollHeight;
    	} 
    	else 
    	{ // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
    		xScroll = document.body.offsetWidth;
    		yScroll = document.body.offsetHeight;
    	}
        
    	var windowWidth, windowHeight;
    	
    	if (self.innerHeight) 
    	{	// all except Explorer
    		if(document.documentElement.clientWidth)
            {
    			windowWidth = document.documentElement.clientWidth; 
    		} 
            else
            {
    			windowWidth = self.innerWidth;
    		}
    		windowHeight = self.innerHeight;
    	} 
        else if (document.documentElement && document.documentElement.clientHeight)
        {   // Explorer 6 Strict Mode
    		windowWidth = document.documentElement.clientWidth;
    		windowHeight = document.documentElement.clientHeight;
    	} 
        else if (document.body)
        {   // other Explorers
    		windowWidth = document.body.clientWidth;
    		windowHeight = document.body.clientHeight;
    	}	
    	
    	// for small pages with total height less then height of the viewport
    	if (yScroll < windowHeight)
        {
    		pageHeight = windowHeight;
    	} else { 
    		pageHeight = yScroll;
    	}
    
    	// for small pages with total width less then width of the viewport
    	if(xScroll < windowWidth){	
    		pageWidth = xScroll;		
    	} else {
    		pageWidth = windowWidth;
    	}
    
    	return [pageWidth, pageHeight];
    }
    
};

Event.observe(document.onresize ? document : window, "resize", function() {
    Windows.ResizeLayers();
    Windows.RecenterWindows();
});
Event.observe(document.onresize ? document : window, "scroll", function() {
    Windows.RecenterWindows();
});
